import React, { useRef, useEffect } from "react";
import { Animated, Text, View, StyleSheet, Button, Easing } from "react-native";

const AnimatedDemo = () => {
  // fadeAnim will be used as the value for opacity. Initial Value: 0
  const fadeAnim = useRef(new Animated.Value(1)).current;
  const moveAnim = useRef(new Animated.Value(0)).current;

  const fadeIn = () => {
    // Will change fadeAnim value to 1 in 5 seconds
    Animated.timing(fadeAnim, {
      toValue: 1,
      duration: 5000,
      useNativeDriver: true,
    }).start();
  };

  const fadeOut = () => {
    // Will change fadeAnim value to 0 in 5 seconds
    Animated.timing(fadeAnim, {
      toValue: 0,
      duration: 5000,
      useNativeDriver: true,
    }).start();
  };

  

  const startAnimation = () => {
    moveAnim.setValue(0);
    Animated.sequence([
      Animated.timing(
        moveAnim,
        {
          toValue: 200,
          duration: 1500,
          easing: Easing.linear,
          useNativeDriver: true,
        }
      )
    ]).start(() => startAnimation())
  };

  useEffect(() => {
    startAnimation()
  });

  return (
    <View style={styles.container}>
      <View>
        <Animated.View
          style={[
            styles.fadingContainer,
            {
              opacity: fadeAnim // Bind opacity to animated value
            }
          ]}
        >
          <Text style={styles.fadingText}>Fading View!</Text>
        </Animated.View>
        <View style={styles.buttonRow}>
          <Button title="淡入" onPress={fadeIn} />
          <Button title="淡出" onPress={fadeOut} />
        </View>
      </View>

      <View style={[styles.scanContainer]}>
        <Animated.View style={[
          styles.border,
          {
            transform: [{
              translateY: moveAnim
            }]
          }
        ]}
        />
      </View>
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    justifyContent: "space-around"
  },
  fadingContainer: {
    paddingVertical: 8,
    paddingHorizontal: 16,
    backgroundColor: "powderblue"
  },
  fadingText: {
    fontSize: 28,
    textAlign: "center",
    margin: 10
  },
  buttonRow: {
    flexDirection: "row",
    justifyContent: 'space-between',
    width: 210,
    marginVertical: 16
  },
  scanContainer: {
    height: 200,
    width: 200,
    borderWidth: 1,
    borderColor: '#00FF00',
    // backgroundColor: 'transparent',
  },
  border: {
    borderWidth: 1,
    borderColor: 'red',
    flex: 0,
    width: 196,
    height: 2,
    backgroundColor: '#fcb602',
    borderRadius: 50
  }
});

export default AnimatedDemo;